/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * addStock.java
 *
 * Created on Oct 31, 2011, 4:49:25 PM
 */

package giormi;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.SQLException;
import javax.swing.JTable;
/**
 *
 * @author Ling
 */
public class addStock extends javax.swing.JFrame {

    /** Creates new form addStock */
    private F_addstock s = new F_addstock();
    private F_updatestock us = new F_updatestock();
    private MainFrame main;
    boolean update;

    private Connection conn;
    private String SQLStatement;
    private String URL;
    private Statement stmt;
    private ResultSet rset;
    protected JTable table;
    private warningFrame wa;
    
    public void setTable(JTable table) {
        this.table = table;
    }
    public void connect(){
        try{
            DBConnection db = new DBConnection();
            conn = DBConnection.get();
            stmt = conn.createStatement();
        }
        catch(Exception e){
            System.out.println(e.getMessage());
            JOptionPane.showMessageDialog(null,e.getMessage(),"ERROR", JOptionPane.WARNING_MESSAGE);
        }
    }

    public void disconnect(){
        try{
            stmt.close();
            conn.close();
        }
        catch(Exception ex){
            System.out.println(ex.getMessage());
            JOptionPane.showMessageDialog(null,ex.getMessage(),"ERROR", JOptionPane.WARNING_MESSAGE);
        }
    }

    public addStock(MainFrame mf, boolean add_update, int stockid) {
        initComponents();
        this.setLocation(400, 150);
        this.setSize(400, 480);
        this.setResizable(false);
        this.setDefaultCloseOperation(javax.swing.JFrame.DO_NOTHING_ON_CLOSE);
        main = mf;
        update = add_update;

        // Add items to product name combo box
        connect();
        try{
            SQLStatement = "SELECT DISTINCT(p_name) from product "
                    + "WHERE p_status = 'Active' ORDER BY p_name";
            rset = stmt.executeQuery(SQLStatement);
            while (rset.next()){
                s_productnameCombox.addItem(rset.getString("p_name"));
            }
            rset.close();
            disconnect();
        }
        catch(Exception ex){
            System.out.println(ex.getMessage());
            JOptionPane.showMessageDialog(null,ex.getMessage(),"ERROR", JOptionPane.WARNING_MESSAGE);
        }


        if(update){
            System.out.println("update:true");
            us.getstock(stockid);
            s_productnameCombox.setSelectedItem(us.getproduct("name"));
            s_packingCombox.setSelectedItem(us.getproduct("packing"));
            receivingdateField.setText(us.getS_datereceived());
            s_totalqtyField.setText(us.getS_quantity());
            s_RRnumField.setText(us.getS_rrnum());
            s_quedanField.setText(us.getS_quedan());
            proddateField.setText(us.getS_proddate());
            expdateField.setText(us.getS_expdate());
            s_lotnumField.setText(us.getS_lotnum());
            s_notesField.setText(us.getS_notes());
        }
    }

    public void setStock(){
        int idproduct = s.getidproduct((String)s_productnameCombox.getSelectedItem(), (String)s_packingCombox.getSelectedItem());

        us.setS_dateposted(date.now());
        us.setS_datereceived(receivingdateField.getText());
        us.setS_expdate(expdateField.getText());
        us.setS_proddate(proddateField.getText());
        us.setS_quantity(s_totalqtyField.getText());
        us.setS_quedan(s_quedanField.getText());
        us.setS_rrnum(s_RRnumField.getText());
        us.setS_lotnum(s_lotnumField.getText());
        us.setS_notes(s_notesField.getText());
        us.setS_idproduct(idproduct);
    }

    public void setcombox(String productname){
        s_productnameCombox.setSelectedItem(productname);

        //Add items to packing combobox
        s_packingCombox.removeAllItems();
        s_packingCombox.addItem("<Select Packing>");
        connect();
        try{
            SQLStatement = "SELECT p_packing from product "+
                            "WHERE p_status = 'Active' AND p_name ='"+(String)s_productnameCombox.getSelectedItem()+
                            "' ORDER BY p_packing";
            rset = stmt.executeQuery(SQLStatement);
            while (rset.next()){
                s_packingCombox.addItem(rset.getString("p_packing"));
            }
            rset.close();
            disconnect();
        }
        catch(Exception ex){
            System.out.println(ex.getMessage());
            JOptionPane.showMessageDialog(null,ex.getMessage(),"ERROR", JOptionPane.WARNING_MESSAGE);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        s_RRnumField = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        s_lotnumField = new javax.swing.JTextField();
        s_totalqtyField = new javax.swing.JTextField();
        s_quedanField = new javax.swing.JTextField();
        s_saveorderButton = new javax.swing.JButton();
        s_cancelorderButton = new javax.swing.JButton();
        s_notesField = new javax.swing.JTextField();
        s_productnameCombox = new javax.swing.JComboBox();
        s_packingCombox = new javax.swing.JComboBox();
        s_searchproductnameButton = new javax.swing.JButton();
        proddateField = new datechooser.beans.DateChooserCombo();
        expdateField = new datechooser.beans.DateChooserCombo();
        receivingdateField = new datechooser.beans.DateChooserCombo();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Manage Stock");
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel2.setText("Product Name");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 30, 100, 20));

        jLabel3.setText("Packing");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 60, 50, 20));

        jLabel4.setText("Receiving Date");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 90, 90, 20));

        jLabel5.setText("Total Quantity");
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 120, 80, 20));

        jLabel6.setText("RR No.");
        getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 150, 100, 20));

        s_RRnumField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                s_RRnumFieldActionPerformed(evt);
            }
        });
        getContentPane().add(s_RRnumField, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 150, 140, -1));

        jLabel8.setText("Production Date");
        getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 210, 100, 20));

        jLabel7.setText("Quedan");
        getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 180, -1, 20));

        jLabel9.setText("Expiry Date");
        getContentPane().add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 240, 80, 20));

        jLabel10.setText("Notes");
        getContentPane().add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 300, 38, 20));

        jLabel11.setText("Lot Number");
        getContentPane().add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 270, 70, 20));

        s_lotnumField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                s_lotnumFieldActionPerformed(evt);
            }
        });
        getContentPane().add(s_lotnumField, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 270, 140, -1));

        s_totalqtyField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                s_totalqtyFieldActionPerformed(evt);
            }
        });
        getContentPane().add(s_totalqtyField, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 120, 40, -1));
        getContentPane().add(s_quedanField, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 180, 140, -1));

        s_saveorderButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/giormi/sources/Save-icon.png"))); // NOI18N
        s_saveorderButton.setText("Save");
        s_saveorderButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                s_saveorderButtonActionPerformed(evt);
            }
        });
        getContentPane().add(s_saveorderButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 370, 100, -1));

        s_cancelorderButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/giormi/sources/Button-Close-icon.png"))); // NOI18N
        s_cancelorderButton.setText("Cancel");
        s_cancelorderButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                s_cancelorderButtonActionPerformed(evt);
            }
        });
        getContentPane().add(s_cancelorderButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 400, 100, -1));

        s_notesField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                s_notesFieldActionPerformed(evt);
            }
        });
        getContentPane().add(s_notesField, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 300, 240, 60));

        s_productnameCombox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<Select Product>" }));
        s_productnameCombox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                s_productnameComboxActionPerformed(evt);
            }
        });
        getContentPane().add(s_productnameCombox, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 30, 210, -1));

        s_packingCombox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<Select Packing>" }));
        getContentPane().add(s_packingCombox, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 60, 140, -1));

        s_searchproductnameButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/giormi/sources/Zoom-icon (1).png"))); // NOI18N
        s_searchproductnameButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                s_searchproductnameButtonActionPerformed(evt);
            }
        });
        getContentPane().add(s_searchproductnameButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 30, 30, 20));
        getContentPane().add(proddateField, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 210, 140, -1));
        getContentPane().add(expdateField, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 240, 140, -1));
        getContentPane().add(receivingdateField, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 90, 140, -1));

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private boolean checkStock(String p_name, String p_packing, String p_datereceived)
    {
            String p_productname, p_packingnum, p_receivingdate;
            p_productname = p_name;
            p_packingnum = p_packing;
            p_receivingdate = p_datereceived;

            if (p_receivingdate.length()!=8)
            p_receivingdate = date.convertDate(p_receivingdate);
            
            String result1, result2, result3;
            Boolean same= false;
            int i=0,nCtr=0;
            connect();
            //3
            System.out.println("pname:"+p_productname+" packing:"+p_packingnum+" receivingdate:"+p_receivingdate);
            SQLStatement = "SELECT *  "
                    + "FROM stock, product "
                    + "WHERE stock.s_idproduct = product.idproduct "
                    + "AND product.p_name = '"+p_productname+"' "
                    + "AND product.p_packing = '"+ p_packingnum+"' "
                    + "AND stock.s_datereceived =  '" + p_receivingdate+"'";
            try {
            rset = stmt.executeQuery(SQLStatement);
            if(rset.next()){
                same=true;
                return same;
            }
            rset.close();
            disconnect();
            } catch (SQLException ex) {
                Logger.getLogger(addProduct.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NullPointerException ex) {
                System.out.println(ex.getMessage());
                return same;
            } catch (Exception ex){
                System.out.println("Same name packing = true");
                warningFrame wa = new warningFrame("stockexists", this);
                wa.setVisible(true);
                same = true;
                return same;
            }
     return same;
    }
    
    private boolean checkValidInputs()
    {
        Boolean valid = false;
        String RRnumber_s, quedan_s, lotnumber_s;
        int RRnumber=0, quedan=0, lotnumber=0, quantity=0;
        
        RRnumber_s = s_RRnumField.getText();
        quedan_s = s_quedanField.getText();
        lotnumber_s = s_lotnumField.getText();
        
        if((RRnumber_s.length()==6)&&(quedan_s.length()==6)&&((lotnumber_s.length()==3)||(lotnumber_s.length()==4)))
        {
           try {
                RRnumber = Integer.parseInt(s_RRnumField.getText());
                quedan = Integer.parseInt(s_quedanField.getText());
                lotnumber = Integer.parseInt(s_lotnumField.getText());
                quantity = Integer.parseInt(s_totalqtyField.getText());
                if(quantity>=0)
                {
                    valid = true;
                }
            }
            catch(NumberFormatException e)
            {
                wa = new warningFrame("invaliddata", this);
                wa.setVisible(true);
            }
        }
        else
        {
            wa = new warningFrame("invaliddata", this);
            wa.setVisible(true);
        }
        return valid;
        
    }
    private void s_RRnumFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_s_RRnumFieldActionPerformed

}//GEN-LAST:event_s_RRnumFieldActionPerformed

    private void s_lotnumFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_s_lotnumFieldActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_s_lotnumFieldActionPerformed

    private void s_totalqtyFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_s_totalqtyFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_s_totalqtyFieldActionPerformed

    private void s_saveorderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_s_saveorderButtonActionPerformed
        // TODO add your handling code here:
        String s_name, s_datereceived, s_packing;
        Boolean same = false, valid=false;
        confirmFrame co;
        
        s_datereceived = receivingdateField.getText();
        s_name = s_productnameCombox.getSelectedItem().toString(); 
        s_packing = s_packingCombox.getSelectedItem().toString();
        
        this.setEnabled(false);
//        s.getidproduct((String)s_productnameCombox.getSelectedItem(), (String)s_packingCombox.getSelectedItem());
        int idproduct = s.getidproduct((String)s_productnameCombox.getSelectedItem(), (String)s_packingCombox.getSelectedItem());

        s.setS_dateposted(date.now());
        s.setS_datereceived(receivingdateField.getText());
        s.setS_expdate(expdateField.getText());
        s.setS_proddate(proddateField.getText());
        s.setS_quantity(s_totalqtyField.getText());
        s.setS_quedan(s_quedanField.getText());
        s.setS_rrnum(s_RRnumField.getText());
        s.setS_lotnum(s_lotnumField.getText());
        s.setS_notes(s_notesField.getText());
        s.setS_idproduct(idproduct);

        
        if((s_totalqtyField.getText()!="")&&(s_RRnumField.getText()!="")&&
                (s_quedanField.getText()!="")&&(s_lotnumField.getText()!="")&&
                (receivingdateField.getText()!="")&&(expdateField.getText()!="")&&
                (s_name!="<Select Product>")&&(s_packing!="<Select Packing>"))
        {
            same = checkStock(s_name,s_packing,s_datereceived);
            if(same)
            {
                wa = new warningFrame("stockexists", this);
                wa.setVisible(true);
            }
            else
            {
                valid = checkValidInputs();
                if (valid){
                    if (update){
                        setStock();
                        co = new confirmFrame(main, this, us, "stock", update);
                    }
                    else
                    co = new confirmFrame(main, this, s, "stock", update);

                    co.setTable(table);
                    co.setVisible(true);
                }
            }
        }
        else
        {
            wa = new warningFrame("invaliddata", this);
            wa.setVisible(true); 
        }
//        warningFrame wa = new warningFrame("stockexists", this);
//        wa.setVisible(true);
//        warningFrame wa2 = new warningFrame("invaliddata", this);
//        wa2.setVisible(true);
//        main.setEnabled(true);
//        this.setVisible(false);
//        this.dispose();
}//GEN-LAST:event_s_saveorderButtonActionPerformed

    private void s_cancelorderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_s_cancelorderButtonActionPerformed
        // TODO add your handling code here:
        main.setEnabled(true);
        this.setVisible(false);
        this.dispose();
}//GEN-LAST:event_s_cancelorderButtonActionPerformed

    private void s_notesFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_s_notesFieldActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_s_notesFieldActionPerformed

    private void s_searchproductnameButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_s_searchproductnameButtonActionPerformed
        // TODO add your handling code here:
        searchproductname_in_addstockorder sp = new searchproductname_in_addstockorder(this, "stock");
        sp.setVisible(true);
        this.setEnabled(false);
    }//GEN-LAST:event_s_searchproductnameButtonActionPerformed

    private void s_productnameComboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_s_productnameComboxActionPerformed
        // TODO add your handling code here:

        //Add items to packing combobox
        s_packingCombox.removeAllItems();
        s_packingCombox.addItem("<Select Packing>");
        connect();
        try{
            SQLStatement = "SELECT p_packing from product "+
                            "WHERE p_status = 'Active' AND p_name ='"+(String)s_productnameCombox.getSelectedItem()+
                            "' ORDER BY p_packing";
            rset = stmt.executeQuery(SQLStatement);
            while (rset.next()){
                s_packingCombox.addItem(rset.getString("p_packing"));
            }
            rset.close();
            disconnect();
        }
        catch(Exception ex){
            System.out.println(ex.getMessage());
            JOptionPane.showMessageDialog(null,ex.getMessage(),"ERROR", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_s_productnameComboxActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private datechooser.beans.DateChooserCombo expdateField;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private datechooser.beans.DateChooserCombo proddateField;
    private datechooser.beans.DateChooserCombo receivingdateField;
    private javax.swing.JTextField s_RRnumField;
    private javax.swing.JButton s_cancelorderButton;
    private javax.swing.JTextField s_lotnumField;
    private javax.swing.JTextField s_notesField;
    private javax.swing.JComboBox s_packingCombox;
    private javax.swing.JComboBox s_productnameCombox;
    private javax.swing.JTextField s_quedanField;
    private javax.swing.JButton s_saveorderButton;
    private javax.swing.JButton s_searchproductnameButton;
    private javax.swing.JTextField s_totalqtyField;
    // End of variables declaration//GEN-END:variables

}
